﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ChoViet.Site.Models;
using ChoViet.Model;
using System.Text;
using System.Security.Cryptography;
using ChoViet.Lib.Common;
using ChoViet.Lib.Mail;
using ChoViet.Lib.MvcMembership;
using System.Configuration;
using ChoViet.Site.Properties;

namespace MAG.Site.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
       // private readonly IPasswordService _passwordService;
        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }
            //_passwordService = new AspNetMembershipProviderWrapper(Membership.Provider);
            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "User/Product", new { id=1});
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Tên đăng nhập hoặc mật khẩu không chính xác!.");
                }

            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {            
            if (ModelState.IsValid)
            {
                if (Request["CaptchaText"] == HttpContext.Session["captchastring"].ToString())
                {
                    // Attempt to register the user                
                    MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        UserProfile profile = UserProfile.GetUserProfile(model.UserName);
                        if (profile == null) profile = new UserProfile();
                        profile.Email = model.Email;
                        profile.FullName = model.FullName;
                        profile.Phone = model.Phone;
                        profile.Address = model.Address;
                        profile.Company = model.Company;
                        profile.NicYahoo = model.Yahoo;
                        profile.NicSkype = model.Skype;
                        profile.Save();
                        string activePasswordBody = "Kích hoạt tài khoản: ";
                        string activePasswordSubject = "[FTC Land] Kích hoạt tài khoản";
                        string fromMail = ConfigurationManager.AppSettings["DefaultFromMail"];
                       
                        try
                        {

                            var u = UserManager.GetMember(model.UserName);
                            var linkAcv = Settings.Default.SiteRootUrl + "account/active?k=" + u.ProviderUserKey.ToString();
                            var body = activePasswordBody + linkAcv;
                            SmtpMailer.sendMail(model.Email, fromMail, activePasswordSubject, body);
                        }
                        catch (Exception exp)
                        {
                            ViewData[Messages.MessageInfo] = exp.Message;
                            return View("RegisterFail");
                        }
                        return View("RegisterSuccess");
                    }
                    else
                    {
                        ViewData[Messages.MessageInfo] = AccountValidation.ErrorCodeToString(createStatus);
                        ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                    }
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.ERR_CAPTCHA_VALIDATE;
                   return View(model);
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }
        public ActionResult Active()
        {
            try
            {
                var k = Request["k"];
                if (k != null && k != string.Empty)
                {
                    //ChoVietDataContext db = new ChoVietDataContext();
                    //var u = db.aspnet_Memberships.Where(e => e.UserId.ToString() == k).FirstOrDefault();
                    //if (u != null)
                    //{
                    //    u.IsApproved = true;
                    //    db.SubmitChanges();
                    //    FormsService.SignIn(u.aspnet_User.UserName, false /* createPersistentCookie */);
                    //    return RedirectToAction("Index", "User/Product");
                    //}
                    return RedirectToAction("Index", "User/Product");
                }
                return RedirectToAction("Index", "Home");
            }
            catch(Exception exp) {
                return RedirectToAction("Index", "Home");
            }
        }

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }
        public ActionResult ResetPassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }
        [HttpPost]
        public ActionResult ResetPassword(RegisterModel model)
        {
            string ResetPasswordBody = "Mật khẩu mới là: ";
            string ResetPasswordSubject = "[FTC] Mật khẩu mới";
            ChoViet.Lib.MvcMembership.AspNetMembershipProviderWrapper a = new ChoViet.Lib.MvcMembership.AspNetMembershipProviderWrapper(System.Web.Security.Membership.Provider);
            var user =UserManager.GetByEmail(Request["txtEmail"]);
            if (user == null) return RedirectToAction("index", "home");
            var newPassword = a.ResetPassword(user);
            string fromMail = ConfigurationManager.AppSettings["DefaultFromMail"];
            var body = ResetPasswordBody + newPassword;
            try
            {
                SmtpMailer.sendMail(user.Email, fromMail, ResetPasswordSubject, body);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View("ResetFail");
            }
            return View("ResetSuccess");
        }
        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Mật khẩu thay đổi không hợp lệ!.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
        //encrypt
        protected string EncryptPassword(string password)
        {
            // Produses an MD5 hash string of the password
            //we use codepage 1252 because that is what sql server uses
            byte[] pwdBytes = Encoding.GetEncoding(1252).GetBytes(password);
            byte[] hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(pwdBytes);
            return Encoding.GetEncoding(1252).GetString(hashBytes);
        }

        //2
        public string GenerateSalt()
        {
            byte[] buf = new byte[16];
            (new RNGCryptoServiceProvider()).GetBytes(buf);
            return Convert.ToBase64String(buf);
        }
        public string EncodePassword(string pass, int passwordFormat, string salt)
        {
            if (passwordFormat == 0) // MembershipPasswordFormat.Clear
                return pass;

            byte[] bIn = Encoding.Unicode.GetBytes(pass);
            byte[] bSalt = Convert.FromBase64String(salt);
            byte[] bAll = new byte[bSalt.Length + bIn.Length];
            byte[] bRet = null;

            Buffer.BlockCopy(bSalt, 0, bAll, 0, bSalt.Length);
            Buffer.BlockCopy(bIn, 0, bAll, bSalt.Length, bIn.Length);
            if (passwordFormat == 1)
            { // MembershipPasswordFormat.Hashed
                HashAlgorithm s = HashAlgorithm.Create("SHA1");
                // Hardcoded "SHA1" instead of Membership.HashAlgorithmType
                bRet = s.ComputeHash(bAll);
            }
            return Convert.ToBase64String(bRet);
        }

    }
}
